﻿using DtoFw;
using DtoFw.Query;
using DtoFw.Result;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI.Common;
using Renci.SshNet.Security;
using Repository;
using Serilog;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Xml.Linq;


namespace SceneEvidenceAPI.Controllers
{
    [Route("api")]
    [AllowAnonymous]
    public class HaiKangController : BaseController
    {
        private readonly PartyService _partyService;
        private readonly RoomService _roomService;
        private readonly MainUserService _userService;
        private readonly MainOrganService _organService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="partyService"></param>
        public HaiKangController(PartyService partyService, RoomService roomService, MainUserService userService, MainOrganService organService)
        {
            this._partyService = partyService;
            this._roomService = roomService;
            this._userService = userService;
            this._organService = organService;
        }

        /// <summary>
        /// 海康获取要开门的数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("queryTransEvidences")]
        public HaiKangTransDto QueryTransEvidences(string tranNo)
        {
            return _partyService.QueryTransEvidences(tranNo);
        }

        /// <summary>
        /// corpCode	单位编号	Y	String	
        ///deviceCode	设备编号	Y	String	
        ///startTime	开始时间	N	String	更新时间
        ///endTime	结束时间	N	String	更新时间
        ///orderby	排序	N	String	
        ///pageNum	当前页	Y	Number	
        ///pageSize	每页返回条数	Y	Number	最大200，默认20
        ////api/v1/cabinet/boxUserList?
        /// </summary>
        [AllowAnonymous]
        [HttpGet("v1/cabinet/boxUserList")]
        public HaiKangBoxUserList GetBoxUserList(string corpCode, string deviceCode, string startTime, string endTime, string orderby, int pageNum, int pageSize)
        {
            return _partyService.GetBoxUserList(corpCode, deviceCode, startTime, endTime, orderby, pageNum, pageSize);
        }

        [AllowAnonymous]
        [HttpPost("user/QueryList")]
        public string QueryUserList()
        {
            string error = "请求参数无效";
            try
            {
                
                var json = new System.IO.StreamReader(Request.Body).ReadToEnd();
                Log.Information($"请求地址：/api/evidence/QueryListByCabinet，\n请求参数：【{json}】");
                if (string.IsNullOrEmpty(json))
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(new { Result = -1, Description = "请求参数无效" });
                }

                var ty = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json, new { key = "", Data = new { deviceCode = "" } });
                if (ty != null)
                {
                    if (ty.key != "WO0SjX9IEUPe17s3LZaevg==")
                    {
                        error = "无权限访问";
                    }
                    else if(ty.Data == null || string.IsNullOrEmpty(ty.Data.deviceCode))
                    {
                        error = "柜子编号不存在";
                    }
                    else
                    {
                        //deviceCode:CE-123，区域号+柜子号+格子号
                        var areaCode = ty.Data.deviceCode.Substring(0, 1);//区域号
                        var cabinetCode = ty.Data.deviceCode.Substring(1, 1);//柜子号
                        //var boxCode = ty.Data.deviceCode.Substring(3); //格子号
                        //验证通过，返回数据
                        var cabinet = _roomService.QueryBoxCabinetNo(areaCode, cabinetCode);

                        if(cabinet != null && cabinet.OrganId > 0)
                        {
                            var org = this._organService.Get(cabinet.OrganId.Value.ToString());
                            //根据柜子所属单位id，查询单位所有用户
                            var userLst = this._userService.QueryByOrgId(cabinet.OrganId.Value);
                            if (userLst == null || userLst.Count == 0)
                            {
                                error = "用户为空";
                            }
                            else
                            {
                                return Newtonsoft.Json.JsonConvert.SerializeObject(new {
                                    Result = 200,
                                    Description = "",
                                    Data = userLst.Select(v => new
                                    {
                                        UserID = v.Id,                 //用户ID
                                        v.Name,                 //警员姓名
                                        PoliceCode = v.PoliceNo,       //警员编号
                                        Password = v.Pwd,              //密码
                                        Salt = v.Salt,
                                        CorpName = org?.Name       //单位名称
                                    })
                                });                            
                            }
                        }
                        else
                        {
                            error = "柜子编号不存在";
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                error = ex.Message;
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(new { Result = -1, Description = error });
        }
        [AllowAnonymous]
        [HttpPost("evidence/QueryListByCabinet")]
        public string QueryEvidenceListByCabinet()
        {
            string error = "请求参数无效";
            try
            {
                var json = new System.IO.StreamReader(Request.Body).ReadToEnd();
                Log.Information($"请求地址：/api/evidence/QueryListByCabinet，\n请求参数：【{json}】");
                if (string.IsNullOrEmpty(json))
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(new { Result = -1, Description = "请求参数无效" });
                }
                var ty = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json, new { key = "", UserID = 0, Data = new { deviceCode = "" , startTime = ""} });
                if (ty != null)
                {
                    if (ty.key != "WO0SjX9IEUPe17s3LZaevg==")
                    {
                        error = "无权限访问";
                    }
                    else if (ty.Data == null || string.IsNullOrEmpty(ty.Data.deviceCode))
                    {
                        error = "柜子编号不存在";
                    }
                    else
                    {
                        //deviceCode:CE-123，区域号+柜子号+格子号
                        var areaCode = ty.Data.deviceCode.Substring(0, 1);//区域号
                        var cabinetCode = ty.Data.deviceCode.Substring(1, 1);//柜子号
                        //var boxCode = ty.Data.deviceCode.Substring(3); //格子号
                        //验证通过，返回数据
                        var cabinet = _roomService.QueryBoxCabinetNo(areaCode, cabinetCode);

                        if (cabinet != null && cabinet.OrganId > 0)
                        {
                            var eviLst = this._roomService.QueryEvidenceByCabinet(cabinet.Id,ty.Data.startTime);
                            return Newtonsoft.Json.JsonConvert.SerializeObject(new
                            {
                                Result = 200,
                                Description = "",
                                Data = new {
                                    LastTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                                    PropertyList = eviLst
                                }
                            });
                        }
                        else
                        {
                            error = "柜子编号不存在";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(new { Result = -1, Description = error });
        }
        [AllowAnonymous]
        [HttpPost("system/GetVersion")]
        public object GetVersion()
        {
            string error = "请求参数无效";
            try
            {
                var json = new System.IO.StreamReader(Request.Body).ReadToEnd();
                if (string.IsNullOrEmpty(json))
                {
                    return new { Result = -1, Description = "请求参数无效" };
                }
                var ty = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json, new { key = "", Data = new { Type = -1 } });
                if (ty != null)
                {
                    if (ty.key != "WO0SjX9IEUPe17s3LZaevg==")
                    {
                        error = "无权限访问";
                    }
                    else
                    {
                        //验证通过，返回数据
                        return Newtonsoft.Json.JsonConvert.SerializeObject(new
                        {
                            Result = 200,
                            Description = "",
                            Data = new
                            {
                                Type = 0,         //升级类型：0 柜子
                                Version = "1.0.0",//版本号
                                Url = "Http:XXXXX"//下载地址
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(new { Result = -1, Description = error });
        }
    }
}
